package xutil

import (
	"errors"

	"strings"

	"gitee.com/wosylf/ltool"
	"gitee.com/wosylf/ltool/encrypt"
	"gitee.com/wosylf/ltool/pkg/xhttp"
)

const (
	快递100地址 = "https://poll.kuaidi100.com/poll/query.do"
)

type S快递100 struct {
	Key      string `json:"key" form:"key"`
	Customer string `json:"customer" form:"key"`
}

func F新建快递100(key, customer string) *S快递100 {
	return &S快递100{Key: key, Customer: customer}
}

// args 1:快递单号，2快递公司，3手机号，如果是顺丰的要传手机号
func (a *S快递100) F快递100查询(num string, args ...string) (by []byte, err error) {
	l := len(args)
	if l == 1 && args[0] == "shunfeng" {
		err = errors.New("顺丰必传手机号")
		return

	}
	bm := make(ltool.BodyMap)
	bm.Set("num", num)
	if l == 1 {
		bm.Set("com", args[0])
	} else if l == 3 {
		bm.Set("com", args[0])
		bm.Set("phone", args[1])
	}
	param := bm.JsonBody()
	bm.Reset()
	sign := strings.ToUpper(encrypt.Md5(param + a.Key + a.Customer)) //生成签名
	bm.Set("sign", sign).Set("customer", a.Customer).Set("param", param)
	//fmt.Println(bm1.EncodeURLParams())
	_, by, err = xhttp.NewClient().Type(xhttp.TypeFormData).SendStruct(bm).Post(快递100地址).EndBytes(ctx)
	return
}

/*
func F快递100查询(bm ltool.BodyMap) (by []byte, err error) {
	if err = bm.CheckEmptyError("com", "num", "customer", "phone", "key"); err != nil { //此处判断一下有没有渠道跟号码
		return
	}

	//先用参数生成param与签名
	bm1 := make(ltool.BodyMap)
	bm1.Set("com", bm.GetString("com")).
		Set("num", bm.GetString("num"))

	if bm.GetString("com") == "shunfeng" {
		if bm.GetString("phone") == ltool.NULL {
			err = errors.New("顺丰手机号必填")
			return
		}
		bm1.Set("phone", bm.GetString("phone"))
	}

	param := bm1.JsonBody()

	bm1.Reset()
	sign := strings.ToUpper(encrypt.Md5(param + bm.GetString("key") + bm.GetString("customer"))) //生成签名
	bm1.Set("sign", sign).Set("customer", bm.GetString("customer")).Set("param", param)
	//fmt.Println(bm1.EncodeURLParams())
	_, by, err = xhttp.NewClient().Type(xhttp.TypeFormData).SendStruct(bm1).Post(快递100地址).EndBytes(ctx)
	//by, err = request.FUrlencoded(快递100地址, bm1.EncodeURLParams())
	//body = string(by)
	return
}
*/
